#!/bin/bash

# 定义URL和本地文件路径
DOWNLOAD_URL="https://factorio.com/get-download/stable/headless/linux64"
DOWNLOAD_DIR="/tmp" # 临时下载目录
LOCAL_FILE="/root/files/linux64"
DOWNLOADED_FILE="${DOWNLOAD_DIR}/linux64" # 假设下载的文件是tar.xz格式

# -------------------------------------------------------------------------------------------
# 尝试下载文件
echo "Downloading Factorio Headless Server..."
wget -P "${DOWNLOAD_DIR}" "${URL}"

# 检查下载是否成功
if [ $? -ne 0 ]; then
    echo "Failed to download Factorio Headless Server."
    exit 1
fi
# 计算下载文件的MD5值
download_file_md5=$(md5sum "${DOWNLOADED_FILE}" | awk '{print $1}')
# -------------------------------------------------------------------------------------------


# -------------------------------------------------------------------------------------------
# 检查本地文件是否存在，不存在，当场解压
if [ ! -f "${LOCAL_FILE}" ]; then
    echo "Installing Factorio Headless Server for the first time..."
    tar -xvf "${DOWNLOADED_FILE}" -C /root/files --strip-components=1
    echo "Factorio Headless Server installed successfully."
fi

# -------------------------------------------------------------------------------------------


# -------------------------------------------------------------------------------------------
# 本地文件存在，则计算md5值
local_file_md5=$(md5sum "${LOCAL_FILE}" | awk '{print $1}')

# 比较MD5值  
if [ "${download_file_md5}" == "${local_file_md5}" ]; then  
    echo "Factorio Headless Server is already up to date."  
else  
    echo "MD5 mismatch, updating Factorio Headless Server..."
    # 删除旧文件  
    rm -f "${LOCAL_FILE}"
  
    # 解压新文件到指定目录  
    tar -xvf "${DOWNLOADED_FILE}" -C /root/files --strip-components=1
  
    # 停止服务器进程  
    server_pid=$(ps -ef | grep "factorio" | head -n 1 | awk '{print $2}')
    if [ -n "$server_pid" ]; then
        kill -SIGTERM "$server_pid"
        if ! kill -0 "$server_pid" &> /dev/null; then
            echo "Server stopped successfully."
        else
            echo "Failed to stop server, using kill -9."
            kill -9 "$server_pid"
        fi
    else
        echo "No Factorio server process found."
    fi
  
    # 拷贝新文件到工作目录
    cp -r "${DOWNLOADED_FILE%/}/factorio/*" /opt/factorio/
  
    # 启动服务器进程
    nohup /opt/factorio/bin/x64/factorio --port 17893 --start-server /opt/factorio/saves/_autosave5.zip --server-settings /opt/factorio/data/server-settings.json &
fi

echo "Factorio Headless Server updated Finished."